#!/usr/bin/env python
# -*- coding:utf-8 -*-

import math

from app import db
from controller.historyInfoController import HistoryInfoController
from controller.userInfoController import UserInfoController
from models.historyInfoModel import HistoryInfo
from models.passageInfoModel import PassageInfo
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings
from utils.validate_operate import verify_operator_object
import time, datetime
import re


class HistoryInfoService(HistoryInfoController):
    @classmethod

    def joint_query(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('AutoID'):
                filter_list.append(cls.AutoID == kwargs.get('AutoID'))
            if kwargs.get('HUserID'):
                filter_list.append(cls.HUserID == kwargs.get('HUserID'))
            if kwargs.get('PassageID'):
                filter_list.append(cls.PassageID == kwargs.get('PassageID'))
            if kwargs.get('IsDelete'):
                filter_list.append(cls.IsDelete == kwargs.get('IsDelete'))
            if kwargs.get('CreateTime'):
                filter_list.append(cls.CreateTime == kwargs.get('CreateTime'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            historyInfo_info = db.session.query(HistoryInfo.AutoID, HistoryInfo.HUserID, HistoryInfo.PassageID,
                                                HistoryInfo.IsDelete, HistoryInfo.CreateTime).filter(*filter_list)

            count = historyInfo_info.count()
            pages = math.ceil(count / size)
            historyInfo_info = historyInfo_info.limit(size).offset((page - 1) * size).all()

            if not historyInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(historyInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def addhistory(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            add_data = {
                'HUserID': kwargs.get('HUserID'),
                'PassageID': kwargs.get('PassageID')
            }
            if kwargs.get('HUserID'):
                filter_list.append(cls.HUserID == kwargs.get('HUserID'))

            historyInfo_info = db.session.query(HistoryInfo.AutoID, HistoryInfo.HUserID, HistoryInfo.PassageID,
                                                HistoryInfo.IsDelete,HistoryInfo.ClickNum, HistoryInfo.CreateTime).filter(
                *filter_list).order_by(cls.ModifyTime.asc())

            count = historyInfo_info.count()

            historyInfo_info = historyInfo_info.all()

            if historyInfo_info:
                results = commons.query_to_dict(historyInfo_info)
                for i in range(0, len(historyInfo_info)):
                    if results[i].get('PassageID') == kwargs.get('PassageID'):
                        ts = time.time()
                        timestamp = datetime.datetime.fromtimestamp(ts)
                        updatedata = {
                            'AutoID': results[i].get('AutoID'),
                            'ClickNum':int(results[i].get('ClickNum'))+1,
                            'ModifyTime': timestamp
                        }
                        res = cls.update(**updatedata)
                        return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count,
                                'data': '更新成功'}
            # 按历史记录情况进行处理
            if count < 10000:
                add_res = cls.add(**add_data)
                return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count,
                        'data': add_res.get('data')}
            elif count >= 10000:
                # 处理返回的数据
                results = commons.query_to_dict(historyInfo_info)
                update_data = {
                    'AutoID': results[0].get('AutoID'),
                    'PassageID': kwargs.get('PassageID')
                }
                update_res = cls.update(**update_data)
                return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count,
                        'data': update_res.get('data')}




        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    @verify_operator_object([99, ], UserInfoController)
    def gethistoryinfo(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('UserID'):
                filter_list.append(cls.HUserID == kwargs.get('UserID'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            historyInfo_info = db.session.query(HistoryInfo.AutoID.label('historyAutoID'), HistoryInfo.HUserID,
                                                HistoryInfo.PassageID,
                                                HistoryInfo.IsDelete, HistoryInfo.ModifyTime.label('CreateTime'), PassageInfo.PostTitle,
                                                PassageInfo.PostType, PassageInfo.DeptType, PassageInfo.PostStatus,
                                                PassageInfo.CommentNum, PassageInfo.UpVoteNum,
                                                PassageInfo.LookNUM,PassageInfo.PostContent).join(PassageInfo,
                                                                          PassageInfo.AutoID == HistoryInfo.PassageID).filter(
                *filter_list).order_by(cls.ModifyTime.desc())

            count = historyInfo_info.count()
            pages = math.ceil(count / size)
            historyInfo_info = historyInfo_info.limit(size).offset((page - 1) * size).all()

            if not historyInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(historyInfo_info)
            for i in range(len(results)):

                img = re.search(r'(?<=(<img src=[\',"])).*?(?=([\',"]))', results[i]['PostContent'])
                if (img):
                    results[i]['img'] = img.group().replace("&amp", "&").replace("&;", "&")
                else:
                    results[i]['img'] = ''
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()

    @classmethod
    def gethistoryinfoV1(cls, **kwargs):
        try:
            filter_list = []
            filter_list.append(cls.IsDelete == 0)
            if kwargs.get('UserID'):
                filter_list.append(cls.HUserID == kwargs.get('UserID'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            historyInfo_info = db.session.query(HistoryInfo.AutoID.label('historyAutoID'), HistoryInfo.HUserID,
                                                HistoryInfo.PassageID,
                                                HistoryInfo.IsDelete, HistoryInfo.ModifyTime.label('CreateTime'),
                                                PassageInfo.PostTitle,
                                                PassageInfo.PostType, PassageInfo.DeptType, PassageInfo.PostStatus,
                                                PassageInfo.CommentNum, PassageInfo.UpVoteNum,
                                                PassageInfo.LookNUM, PassageInfo.PostContent).join(PassageInfo,
                                                                                                   PassageInfo.AutoID == HistoryInfo.PassageID).filter(
                *filter_list).order_by(cls.ModifyTime.desc())

            count = historyInfo_info.count()
            pages = math.ceil(count / size)
            historyInfo_info = historyInfo_info.limit(size).offset((page - 1) * size).all()

            if not historyInfo_info:
                return {'code': RET.NODATA, 'message': error_map_EN[RET.NODATA], 'error': 'No data to update'}

            # 处理返回的数据
            results = commons.query_to_dict(historyInfo_info)
            for i in range(len(results)):

                img = re.search(r'(?<=(<img src=[\',"])).*?(?=([\',"]))', results[i]['PostContent'])
                if (img):
                    results[i]['img'] = img.group().replace("&amp", "&").replace("&;", "&")
                else:
                    results[i]['img'] = ''
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'error': str(e)}
        finally:
            db.session.close()